/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package database;

import java.util.Calendar;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import rentaldb.Lease;
import rentaldb.Property;

/**
 *
 * @author Pop
 */
public class LeaseDao {
    private EntityManager em;
    private EntityManagerFactory emf;
    
    public LeaseDao(){
        try{
            emf = Persistence.createEntityManagerFactory("RentaldbPU");
            em = emf.createEntityManager();  
        }catch(Exception e){ System.out.println(e);}
    }
    
    public void persist(Lease l){
        em.getTransaction().begin();
        em.persist(l);
        em.getTransaction().commit();
        
    }
    
    public void update(Lease l){
        em.getTransaction().begin();
        em.merge(l);
        em.getTransaction().commit();
    }
    
    public void delete(Lease l) throws Exception{
        l = getLeaseById(l.getLeaseid());
        em.getTransaction().begin();
        em.remove(l);
        em.getTransaction().commit();
    }
    
    public Lease getLeaseById(Integer id) throws Exception{
        //em.createQuery("select * from property");
        Query q = em.createNamedQuery("Lease.findByLeaseid");
        q.setParameter("leaseid", id);
        Lease l = (Lease)q.getSingleResult();
        
        return l;
    }
    
    public List<Lease> getAllLeases() throws Exception{
        Query q = em.createNamedQuery("Lease.findAll");
        List<Lease> leaseList = q.getResultList();
        
        return leaseList;
    }
    
    public Lease getCurrentLeaseForProperty(Property prop, Calendar currentDate){
        Query q = em.createNamedQuery("Lease.findByPropIdAndEndDate");
        q.setParameter("propertyid", prop);
        q.setParameter("enddate", currentDate.getTime());
        Lease l = (Lease)q.getSingleResult();
        return l;
    }
}

